package gait.cannon.web.controller;

import gait.cannon.bean.User;
import gait.cannon.dao.UserDao;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/user")
public class UserController {

	public final Log log = LogFactory.getLog(getClass());
	
	private UserDao userDao;
	private String VIEW_TAG = "userCenter";
	
	@Resource
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	@RequestMapping("/list")
	public ModelAndView list() {
		ModelAndView mv = new ModelAndView(VIEW_TAG);
		mv.addObject("users", userDao.list());
		return mv;
	}
	
	@RequestMapping("/insert")
	public ModelAndView insert(@RequestParam ("username") String username, @RequestParam ("password") String password) {
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		ModelAndView mv = new ModelAndView(VIEW_TAG);
		userDao.insert(user);
		mv.addObject("users", userDao.list());
		return mv;
	}
	
	@RequestMapping("/delete/{id}")
	public ModelAndView delete(@PathVariable ("id") Integer id) {
		userDao.delete(id);
		ModelAndView mv = new ModelAndView(VIEW_TAG);
		mv.addObject("users", userDao.list());
		return mv;
	}
	
}
